<template>
  <div
    v-loading="loading"
    class="monthPlanAdd"
  >
    <div class="pub-detail-title-btn">
      <template v-if="state !== 3">
        <a-button
          type="primary"
          :loading="loadingData.add"
          icon="plus"
          @click="addRow('add')"
        >
          添加行
        </a-button>
        <a-button
          type="danger"
          icon="delete"
          @click="handleDel"
        >
          删除行
        </a-button>
      </template>
      <template>
        <excel
          ref="exportSelect"
          file-name="项目物资需用总计划"
          is-click-generate="false"
        >
          <a-button
            slot="excelBtn"
            icon="download"
            type="primary"
            :disabled="selectedRowKeys.length == 0"
            @click="exportSelect"
          >
            导出选中
          </a-button>
        </excel>
        <excel
          ref="exportAll"
          file-name="项目物资需用总计划"
          is-click-generate="false"
        >
          <a-button
            slot="excelBtn"
            icon="download"
            type="primary"
            @click="exportAll"
          >
            导出全部
          </a-button>
        </excel>
      </template>
      <template v-if="state !== 3">
        <a-button
          v-if="state !== 3"
          icon="download"
          type="primary"
          :loading="loadingData.download"
          @click="addRow('download')"
        >
          标准模板下载
        </a-button>
        <!-- 导入 -->
        <ExcelImportButton
          v-if="state !== 3"
          ref="excelImportButton"
          v-btnPermission="'lu_0014_imp_05'"
          icon="import"
          class="ml12"
          @handleSubmit="handleSubmit"
        />
      </template>
    </div>
    <a-table
      ref="table"
      :pagination="false"
      :columns="columns"
      :data-source="data"
      bordered
      class="bgFFF"
      :scroll="{ x: 1300 }"
      row-key="id"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <span
        slot="index"
        slot-scope="text, record, index"
      >{{ index + 1 }}</span>
      <template
        v-for="col in [
          'materialName',
          'materialCode',
          'materialModel',
          'materialUnit',
          'baseNeedNum',
          'mainNeedNum',
          'decorationNeedNum',
          'subtotalNum',
          'otherNum',
          'totalNum',
          'supplyAuthStr',
          'remark'
        ]"
        :slot="col"
        slot-scope="text, record"
      >
        <div
          :key="col"
          class="form-item"
        >
          <template v-if="state !== 3">
            <a-select
              v-if="col === 'supplyAuthStr'"
              v-model="record.supplyAuth"
              @blur="save(record)"
            >
              <a-select-option
                v-for="item in optionArr"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
            <BaseInput
              v-else-if="
                col === 'remark' ||
                  col === 'materialCode' ||
                  col === 'materialName' ||
                  col === 'materialModel' ||
                  col === 'materialUnit'
              "
              v-model="record[col]"
              :class="col === 'remark' ? 'remark' : ''"
              :show-tip-length="5"
              :disabled="
                col === 'materialCode' ||
                  col === 'materialName' ||
                  col === 'materialModel' ||
                  col === 'materialUnit'
              "
              style="margin: -5px 0"
              @blur="save(record)"
            />
            <BaseInputNumber
              v-else
              v-model="record[col]"
              :show-tip-length="2"
              :precision="3"
              :disabled="col === 'subtotalNum' || col === 'totalNum'"
              style="margin: -5px 0"
              @change="change(record)"
              @blur="save(record)"
            />
          </template>
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
    </a-table>
    <pagination
      v-model="pageNo"
      :total="totalSize"
      :page-size.sync="pageSize"
      @change="handlePageChange"
      @showSizeChange="showSizeChange"
    />
    <materialListAndDir
      ref="detailDialog"
      @createList="createList"
    />
  </div>
</template>
<script>
import {
    goodsList,
    goodsListAdd,
    goodsListDel,
    goodsListEdit,
    downloadExcel
} from '@/api/material/materialMasterPlan/materialPlan'
import { materialColumns } from './insideModel'
import { selectOption } from '@/api/material/goods/goods'
import materialListAndDir from '@/components/materialListAndDir/materialListAndDir'
const data = []
export default {
    name: 'RebarPlan',
    props: {
        state: {
            type: Number
        },
        id: {
            type: String
        }
    },
    components: {
        materialListAndDir
    },
    data() {
        this.cacheData = data.map((item) => ({ ...item }))
        return {
            loading: false,
            pageNo: 1,
            tempData: null,
            pageSize: 10,
            totalSize: 0,
            selectedRowKeys: [],
            columns: materialColumns,
            editingKey: '',
            data: this.tableData,
            optionArr: [],
            selectedId: [],
            supplyAuth: null,
            downloadExcel: downloadExcel,
            rules: {
                baseNeedNum: [{ rule: 'required', message: '基础需用数量不能为空' }],
                mainNeedNum: [{ rule: 'required', message: '主体需用数量不能为空' }],
                decorationNeedNum: [{ rule: 'required', message: '装修需用数量不能为空' }],
                otherNum: [{ rule: 'required', message: '其他数量不能为空' }],
                supplyAuth: { rule: 'required', message: '供应权限不能为空' }
            },
            loadingData: {
                add: false,
                download: false
            },
            importCheck: {
                物资名称: 'materialName',
                物料编码: 'materialCode',
                规格型号: 'materialModel',
                计量单位: 'materialUnit',
                基础需用数量: 'baseNeedNum',
                主体需用数量: 'mainNeedNum',
                装修需用数量: 'decorationNeedNum',
                其他数量: 'otherNum',
                供应权限: 'supplyAuthStr',
                备注: 'remark'
            } // 导入字段对应
        }
    },
    watch: {},
    mounted: function () {
        this.getOption()
        if (this.state === 3) {
            this.editingKey = true
        }
        this.list()
        this.initErrMessage(this.rules)

        this.$refs.exportSelect.tableToExcelFile(this.$refs.table)
        this.$refs.exportAll.tableToExcelFile(this.$refs.table)
    },
    methods: {
        createList(data) {
            let params = []
            data.forEach((item) => {
                params.push({
                    baseNeedNum: null,
                    decorationNeedNum: null,
                    mainNeedNum: null,
                    materialCode: item.code,
                    materialModel: item.specificationModel,
                    materialName: item.name,
                    materialUnit: item.unitId,
                    otherNum: null,
                    projectId: this.id,
                    remark: '',
                    subtotalNum: 0,
                    supplyAuth: null,
                    totalNum: 0,
                    materialId: item.id
                })
            })

            this.loading = true
            goodsListAdd(params).then((res) => {
                if (res.code === 200) {
                    this.initTable()
                }
                this.loading = false
            })
        },
        change(record) {
            console.log(record)
            record['subtotalNum'] =
                Number(record['baseNeedNum']) + Number(record['mainNeedNum']) + Number(record['decorationNeedNum'])
            record['totalNum'] = Number(record['subtotalNum']) + Number(record['otherNum'])
        },
        async addRow(type) {
            let temp = []
            if (this.totalSize !== 0) {
                this.loadingData[type] = true
                let res = await goodsList({
                    pageSize: this.totalSize,
                    pageNo: 1,
                    id: this.id
                })
                this.loadingData[type] = false
                temp = res.data
            }
            if (type === 'add') {
                this.$refs.detailDialog.open(temp)
            } else {
                this.$refs.detailDialog.download(temp, this.downloadExcel, { type: 3 })
            }
        },
        getOption: function () {
            let _this = this
            selectOption({
                type: 14
            }).then((res) => {
                if (res.code === 200) {
                    _this.optionArr = res.data
                }
            })
        },
        // 删除
        handleDel() {
            this.loading = !!this.selectedId.length
            this.delList2(
                goodsListDel,
                () => {
                    this.pageNo =
                        this.pageNo - 1 < (this.totalSize - this.selectedId.length) / this.pageSize
                            ? this.pageNo
                            : this.pageNo - 1
                    this.list()
                    this.selectedId = []
                    this.selectedRowKeys = []
                    this.selectedRows = []
                    this.editingKey = ''
                    this.loading = false
                },
                { ids: this.selectedId },
                () => {
                    this.loading = false
                }
            )
        },
        initTable() {
            this.pageNo = 1
            this.list()
        },
        list(callback) {
            let _this = this
            this.loading = true
            goodsList({
                pageSize: callback ? this.totalSize : this.pageSize,
                pageNo: _this.pageNo,
                id: _this.id
            }).then((res) => {
                if (res.code === 200) {
                    if (callback) {
                        if (res.data.length) {
                            const exportData = this.$clone(res.data)
                            exportData.map((i) => {
                                i.supplyAuth = i.supplyAuthStr
                                i.subtotalNum += ''
                                i.baseNeedNum += ''
                                i.totalNum += ''
                                i.mainNeedNum += ''
                                return i
                            })

                            callback(res.data)
                        } else {
                            this.$message.warning('没有可导出的数据')
                        }
                        this.loading = false
                        return
                    }
                    _this.data = res.data
                    _this.totalSize = res.totalSize
                }
                this.loading = false
            })
        },
        // list() {
        //     this.loading = true
        //     let _this = this
        //     goodsList({ pageSize: _this.pageSize, pageNo: _this.pageNo, id: _this.id }).then((res) => {
        //         if (res.code === 200) {
        //             _this.data = res.data
        //             _this.totalSize = res.totalSize
        //         }
        //         this.loading = false
        //     })
        // },
        handlePageChange(pageNo, pageSize) {
            this.selectedId = []
            this.selectedRowKeys = []
            this.selectedRows = []
            this.pageNo = pageNo
            this.list()
        },
        showSizeChange(pageNo, pageSize) {
            this.pageSize = pageSize
            this.initTable()
        },
        async save(row) {
            row.supplyAuthStr = this.optionArr.filter((i) => i.id == row.supplyAuth)[0].name
            await goodsListEdit(row)
        },
        exportSelect: function () {
            if (this.selectedRowKeys.length > 0) {
                const exportData = this.$clone(this.selectedRows)
                exportData.map((i) => {
                    i.supplyAuth = i.supplyAuthStr
                    i.subtotalNum += ''
                    i.baseNeedNum += ''
                    i.totalNum += ''
                    i.mainNeedNum += ''
                    return i
                })
                console.log(exportData)
                this.$refs.exportSelect.setDataAndGenerate(exportData)
            } else {
                this.$message.warning('请选择需要导出的数据')
            }
        },
        exportAll: function () {
            // 参数：查询条件、导出的回调
            if (this.totalSize) {
                this.pageNo = 1
                this.list(this.$refs.exportAll.setDataAndGenerate)
            } else {
                this.$message.warning('没有可导出的数据')
            }
        },
        onSelectChange(selectedRowKeys, selectedRows) {
            this.selectedId = []
            selectedRows.map((i) => {
                this.selectedId.push(i.id)
            })
            this.selectedRowKeys = selectedRowKeys
            this.selectedRows = selectedRows
        },
        /**
         * 导入记录
         */

        handleSubmit(e) {
            let form = []
            console.log(e)
            for (let index in e) {
                form.push({})
                let keys = e[index]
                let listItem = form[index]
                // 校验excel的表头数量
                // if (Object.keys(keys)?.length === 7) {
                // 校验excel的表头字段
                for (let i in this.importCheck) {
                    let item = this.importCheck[i]
                    if (
                        !Object.keys(keys).includes(i) &&
                        (i == '基础需用数量' || i == '主体需用数量' || i == '装修需用数量' || i == '其他数量')
                    ) {
                        this.$message.warning(`${i}必填`)
                        return
                    } else {
                        listItem[item] = keys[i]
                        if (
                            item == 'baseNeedNum' ||
                            item == 'mainNeedNum' ||
                            item == 'decorationNeedNum' ||
                            item == 'otherNum'
                        ) {
                            if (isNaN(parseInt(listItem[item]))) {
                                this.$message.warning(`${i}必须为数字`)
                                return
                            }
                        }
                        listItem.projectId = this.id
                    }
                }
                // } else {
                //     this.$message.warning('数据不完整')
                //     return
                // }
            }
            this.loading = true
            goodsListAdd(form).then(
                (res) => {
                    console.log(res)
                    this.$message.success('导入成功')
                    this.loading = false
                    this.initTable()
                },
                (error) => {
                    console.log(error)
                    const errors = error.data.message.split('/')
                    if (errors.length > 0) {
                        this.$info({
                            title: '提示',
                            width: '650px',
                            content: function () {
                                return errors.map((i, index) => (
                                    <p style="margin-bottom: 10px;">
                                        {index + 1 > 2 ? index - 1 + ':' : ''}
                                        {i}
                                    </p>
                                ))
                            },
                            onOk() {}
                        })
                    }

                    this.loading = false
                }
            )
        }
    }
}
</script>
<style lang="less" scoped>
/deep/ .form-item  {
    .ant-input:not([disabled]),
    .ant-select:not(.ant-select-disabled) .ant-select-selection,
    .ant-calendar-picker-input,
    .ant-input-number-input,
    .ant-cascader-picker {
        border-color: #e4ac0b;
        background-color: #fff9e8;
    }
    .remark {
        .ant-input {
            border-color: inherit;
            background-color: initial;
        }
    }
}
</style>